package com.jus.player.util;

import static android.content.Context.MODE_PRIVATE;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;


import com.facebook.login.LoginManager;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.jus.player.R;
import com.jus.player.activity.LoginActivity;
import com.jus.player.api.ApiConfig;
import com.jus.player.api.OkHttpHelper;
import com.jus.player.config.AppConfig;
import com.jus.player.entity.BannerEntity;
import com.jus.player.fragment.play.VideoListFragment;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.InetAddress;
import java.util.Currency;
import java.util.HashMap;
import java.util.Locale;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * APP公共方法类（Toast提示，SP存取，导航到页面navigate）
 */
public class CommonUtils {

    /**
     * toast 距离底部最小值
     */
    private static final int minYOffset = 100;

    /**
     * 提示Toast
     *
     * @param msg      提示信息
     * @param activity context
     */
    public static void showToast(Activity activity, String msg) {
        showToast(activity, msg, Toast.LENGTH_SHORT);
    }

    public static void showToast(Activity activity, String msg, int duration) {
        showToast(activity, msg, duration, minYOffset);
    }


    public static void showToastPos(Activity activity, String msg, int yOffset, boolean top) {

        // 获取屏幕高度
        DisplayMetrics displayMetrics = new DisplayMetrics();
        ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE))
                .getDefaultDisplay().getMetrics(displayMetrics);
        int screenHeight = displayMetrics.heightPixels;
        int result = yOffset;
        if (top) {
            result = screenHeight - yOffset;
        }
        showToast(activity, msg, Toast.LENGTH_SHORT, result);
    }

    public static void showToast(Activity activity, String msg, int duration, int yOffset) {
        // 创建自定义 Toast
        yOffset = Math.max(yOffset, minYOffset);
        View layout = activity.getLayoutInflater().inflate(R.layout.layout_toast, null);
        /*ImageView image = layout.findViewById(R.id.toast_image);
        image.setImageResource(R.drawable.ic_info40);*/
        TextView text = layout.findViewById(R.id.toast_text);
        text.setText(msg);
        Toast toast = new Toast(activity.getApplicationContext());
        toast.setGravity(Gravity.BOTTOM, 0, yOffset);
        toast.setDuration(duration);
        toast.setView(layout);
        toast.show();
    }

    /**
     * 异步 提示Toast
     *
     * @param activity activity
     * @param msg      msg
     */
    public static void showToastAsync(Activity activity, String msg) {
        showToastAsync(activity, msg, Toast.LENGTH_SHORT);
    }

    public static void showToastAsync(Activity activity, String msg, int duration) {
        showToastAsync(activity, msg, duration, minYOffset);
    }

    public static void showToastAsync(Activity activity, String msg, int duration, int yOffset) {
        Handler mainHandler = new Handler(Looper.myLooper() == null
                ? Looper.getMainLooper() : Looper.myLooper());
        mainHandler.post(() -> showToast(activity, msg, duration, yOffset));
    }

    /**
     * 保存数据到SharedPreferences
     *
     * @param context context
     * @param key     key
     * @param val     val
     */
    public static void insertToSp(Context context, String key, String val) {
        SharedPreferences sp = context.getSharedPreferences(AppConfig.SP_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit().putString(key, val);
        editor.apply();
    }

    /**
     * 从SharedPreferences获取值
     *
     * @param key 保存时的key
     * @return value
     */
    public static String findFromSp(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(AppConfig.SP_NAME, MODE_PRIVATE);
        return sp.getString(key, "");
    }

    /**
     * 清除SP文件的指定key数据
     */
    public static void removeSP(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(AppConfig.SP_NAME, MODE_PRIVATE);
        sp.edit().remove(key).apply();
    }

    /**
     * 清空SP文件
     *
     * @param context context
     */
    public static void clearSP(Context context) {
        context.getSharedPreferences(AppConfig.SP_NAME, MODE_PRIVATE)
                .edit().clear().apply();
    }

    /**
     * 导航到指定页面
     *
     * @param clazz 目标页面
     */
    public static void navigateTo(Context context, Class<?> clazz) {
        context.startActivity(new Intent(context, clazz));
    }

    /**
     * 导航到指定页面并 回退堆栈，创建新的task
     *
     * @param clazz 目标页面
     */
    public static void navigateTo(Context context, Class<?> clazz, int flag) {
        Intent intent = new Intent(context, clazz);
        intent.setFlags(flag);
        context.startActivity(intent);
    }

    /**
     * loading 加载动画展示
     *
     * @param activity
     * @return View
     */
    @SuppressLint("StaticFieldLeak")
    private static View loadingView;

    public static View showLoading(Activity activity) {
        // 初始化加载视图
        loadingView = activity.getLayoutInflater().inflate(R.layout.custom_loading,
                activity.findViewById(android.R.id.content), false);
        ((ViewGroup) activity.findViewById(android.R.id.content)).addView(loadingView);

        activity.runOnUiThread(() -> {
            loadingView.setVisibility(View.VISIBLE);
            activity.getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                    WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
            );
        });
        return loadingView;
    }

    public static void hideLoading(Activity activity) {
        if (loadingView != null) {
            activity.runOnUiThread(() -> {
                loadingView.setVisibility(View.GONE);
                activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
                loadingView = null;
            });
        }
    }

    /**
     * 检查网络是否可用
     *
     * @param context context
     * @return boolean
     */
    public static boolean isNetworkConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
        }
        return false;
    }

    /**
     * google网络检查回掉接口
     */
    public interface NetworkCheckCallback {
        void onResult(boolean isAvailable);
    }

    /**
     * 检测Google服务是否可用
     */
    public static void isGoogleServicesAvailable(Context context, NetworkCheckCallback callback) {

        // 第一部分：检查Google Play服务是否安装并可用（同步）
        GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
        int resultCode = apiAvailability.isGooglePlayServicesAvailable(context);
        if (resultCode != ConnectionResult.SUCCESS) {
            callback.onResult(false);
            return;
        }
        // 第二部分：在后台线程检查网络连通性（异步）
        Executors.newSingleThreadExecutor().execute(() -> {
            boolean finalResult = checkSpecificDomain("accounts.google.com", 5000);
            new Handler(Looper.getMainLooper()).post(() -> {
                callback.onResult(finalResult);
            });
        });
    }

    /**
     * 检测Facebook服务是否可用
     */
    public static void checkFacebookAvailable(Context context, NetworkCheckCallback callback) {

        // 在后台线程检查网络连通性（异步）
        Executors.newSingleThreadExecutor().execute(() -> {
            // 检测Facebook核心域名可达性
            boolean canReachFacebook = checkSpecificDomain("graph.facebook.com", 5000);
            //&& checkSpecificDomain("connect.facebook.net", 3000);
            // 额外检测外网连通性（通过Google DNS验证）
            //boolean canAccessInternet = checkSpecificDomain("8.8.8.8", 3000);
            new Handler(Looper.getMainLooper()).post(() -> {
                callback.onResult(canReachFacebook);
            });
        });
    }

    //检测Facebook核心域名可达性
    private static boolean checkSpecificDomain(String host, int timeout) {
        try {
            return InetAddress.getByName(host).isReachable(timeout);
        } catch (IOException e) {
            return false;
        }
    }


    /**
     * 退出登陆逻辑
     */
    public static void logout(Activity activity) {
        // 清除SharedPreferences
        CommonUtils.clearSP(activity);
        // 清除文件缓存
        signOut(activity);
        navigateTo(activity, LoginActivity.class,
                Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.finish();
    }


    /**
     * 触发Google和facebook登出流程。
     */
    private static void signOut(Activity activity) {
        LoginManager.getInstance().logOut();
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(activity.getString(R.string.web_oauth_client_id)) // 替换为你的OAuth 2.0客户端ID
                .requestEmail() // 请求用户的电子邮件地址
                .build();
        //创建一个GoogleSignInClient实例
        GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(activity, gso);
        mGoogleSignInClient.signOut();
    }

    /**
     * 价格汇率计算
     */
    public static class ExchangeRateManager {

        private static final String KEY_RATES_JSON = "exchange_rates";
        private static final String KEY_LAST_UPDATE = "last_update";
        private static final String RATES = "conversion_rates";
        // 24小时缓存
        private static final long CACHE_DURATION = TimeUnit.HOURS.toMillis(24);

        private final Context context;
        private JSONObject ratesJson;
        private final OkHttpClient httpClient;

        public ExchangeRateManager(Context context) {
            this.context = context.getApplicationContext();
            this.httpClient = new OkHttpClient();
            loadCachedRates();
        }

        // 获取当地货币价格
        public String getLocalPrice(double usdPrice) {
            try {
                getGoogleAccountCountry(context);
                String currencyCode = getLocalCurrencyCode();
                double rate = getExchangeRate(currencyCode);
                double localPrice = usdPrice * rate;
                return formatCurrency(localPrice, currencyCode);
            } catch (Exception e) {
                Log.e("ExchangeRateManager", "Error converting price", e);
                return formatCurrency(usdPrice, "USD"); // 失败时回退显示美元
            }
        }

        public static String getGoogleAccountCountry(Context context) {
            try {
                AccountManager accountManager = AccountManager.get(context);
                Account[] accounts = accountManager.getAccountsByType("com.google");

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        // 获取当地货币代码
        public String getLocalCurrencyCode() {
            try {
                Locale locale = Locale.getDefault();
                return Currency.getInstance(locale).getCurrencyCode();
            } catch (IllegalArgumentException e) {
                return "USD"; // 默认美元
            }
        }

        // 获取汇率
        private double getExchangeRate(String currencyCode) throws JSONException {
            if (currencyCode.equals("USD")) return 1.0;

            if (ratesJson == null) {
                getExchangeRate(currencyCode);
            }
            if (!ratesJson.has(currencyCode)) {
                throw new JSONException("Currency not found: " + currencyCode);
            }
            return ratesJson.getDouble(currencyCode);
        }

        // 格式化货币
        private String formatCurrency(double amount, String currencyCode) {
            Currency currency = Currency.getInstance(currencyCode);
            java.text.NumberFormat format = java.text.NumberFormat.getCurrencyInstance();
            format.setCurrency(currency);
            return format.format(amount);
        }

        // 从缓存加载汇率
        private void loadCachedRates() {
            String ratesJsonStr = findFromSp(context, KEY_RATES_JSON);
            if (!StringUtils.isEmpty(ratesJsonStr)) {
                try {
                    ratesJson = new JSONObject(ratesJsonStr);
                } catch (JSONException e) {
                    Log.e("ExchangeRateManager", "Error parsing cached rates", e);
                }
            }
        }

        // 检查并更新汇率
        public void updateRatesIfNeeded() {
            if (shouldUpdate()) {
                new Thread(this::fetchLatestRates).start();
            }
        }
        // 检查是否需要更新
        private boolean shouldUpdate() {
            SharedPreferences prefs = context.getSharedPreferences(AppConfig.SP_NAME, Context.MODE_PRIVATE);
            String rateJson = prefs.getString(KEY_RATES_JSON, null);
            if (rateJson == null) {
                return true;
            }
            long lastUpdate = prefs.getLong(KEY_LAST_UPDATE, 0);
            return System.currentTimeMillis() - lastUpdate > CACHE_DURATION;
        }

        // 获取最新汇率
        private void fetchLatestRates() {
            // 使用免费汇率API (示例使用Fixer.io的免费端点)
            String apiKey = "448ef5f77c267f543ae5961e"; // 替换为你的API key
            String url = "https://v6.exchangerate-api.com/v6/" + apiKey + "/latest/USD";
            Request request = new Request.Builder().url(url).build();
            try (Response response = httpClient.newCall(request).execute()) {
                if (response.isSuccessful() && response.body() != null) {
                    String jsonStr = response.body().string();
                    JSONObject json = new JSONObject(jsonStr);
                    if (json.has("conversion_rates")) {
                        ratesJson = json.getJSONObject(RATES);
                        Log.e("汇率数据==》RATES", ratesJson.toString());
                        // 缓存新汇率
                        SharedPreferences prefs = context.getSharedPreferences(AppConfig.SP_NAME, Context.MODE_PRIVATE);
                        prefs.edit()
                                .putString(KEY_RATES_JSON, ratesJson.toString())
                                .putLong(KEY_LAST_UPDATE, System.currentTimeMillis())
                                .apply();
                    }
                }
            } catch (IOException | JSONException e) {
                Log.e("ExchangeRateManager", "Error fetching rates", e);
            }
        }

    }

}
